/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package com.moon.admin.framework.mybatisplus;

import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.moon.admin.framework.MoonConstants;
import com.moon.admin.framework.mybatisplus.props.JdbcProperties;
import com.moon.admin.framework.mybatisplus.props.MoonTenantProperties;
import com.moon.admin.framework.mybatisplus.tenant.DynamicMultipleDataSource;
import com.moon.admin.framework.secure.AuthUtils;
import com.moon.admin.framework.util.ToolUtils;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * mybatis plus 插件配置
 * @author moon
 */
@AutoConfigureAfter({com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration.class})
@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
@Slf4j
public class MoonMybatisPlusAutoConfiguration {
	
	@Autowired
	private MoonTenantProperties moonTenantProperties;
    @Autowired
    private JdbcProperties jdbcProperties;

	/**
     * 新多租户插件配置,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存万一出现问题
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        if(MoonConstants.TenantTypeEnum.cloumn.ordinal()==moonTenantProperties.getType()){
            log.info("系统已开启cloumn级别的租户数据模式....");
            interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
                @Override
                public Expression getTenantId() {
                    return new StringValue(ToolUtils.toStr(AuthUtils.getTenantCode(), MoonConstants.DEFAULT_TENANT_CODE));
                }
                @Override
                public String getTenantIdColumn() {
                    return moonTenantProperties.getColumn();
                }
                @Override
                public boolean ignoreTable(String tableName) {
                    if(ToolUtils.isBlank(AuthUtils.getTenantCode())){
                        return true;
                    }
                    if(moonTenantProperties.getMoonTables().contains(tableName.toLowerCase())){
                        return true;
                    }
                    if(moonTenantProperties.getTables().size() > 0 && moonTenantProperties.getTables().contains(tableName.toLowerCase())){
                        return true;
                    }
                    return false;
                }
            }));
        }
//        interceptor.addInnerInterceptor(new DataPermissionInterceptorHandler());
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }

	@Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }

    /**
     * 初始化多数据源
     * @return
     */
    @Bean("dataSource")
    @ConditionalOnProperty(value = "moon.tenant.type", havingValue= "2")
    public DynamicMultipleDataSource multipleDataSource () {
        log.info("系统已开启datasource级别的租户数据模式....");
        DynamicMultipleDataSource dynamicMultipleDataSource = new DynamicMultipleDataSource();
        Map< Object, Object > targetDataSources = new HashMap<>();
        HikariDataSource hikariDataSource = DynamicMultipleDataSource.buildDataSource(jdbcProperties.getJdbcPool());
        hikariDataSource.setUsername(jdbcProperties.getUsername());
        hikariDataSource.setPassword(jdbcProperties.getPassword());
        hikariDataSource.setJdbcUrl(jdbcProperties.getUrl());
        String dsName = "default";
        targetDataSources.put(dsName, hikariDataSource );
        //设置默认数据源
        DynamicMultipleDataSource.dataSourcesMap.put(dsName,hikariDataSource);
        dynamicMultipleDataSource.setTargetDataSources( targetDataSources );
        return dynamicMultipleDataSource;
    }

    /**
     * 数据权限插件
     * @return DataScopeInterceptor
     */
//    @Bean
//    @ConditionalOnProperty(value = "moon.dataScope.enable",matchIfMissing=false )
//    public DataScopeInterceptorHandler dataScopeInterceptor() {
//        return new DataScopeInterceptorHandler();
//    }
}